from elasticsearch import  Elasticsearch
class Esoper:
    def __init__(self):
        self.index="img_index";
        self.type="test-type";
        self.es=Elasticsearch([{'host':'120.27.134.34','port':'9200'}]);
    def searchBytag(self,imgtags):
        res=self.es.search(index=self.index,doc_type=self.type,body={
            "query":{
                "terms":{"tags":imgtags}

            }
        })
        v=[]
        for hit in res['hits']['hits']:
            v.append(hit["_source"])
        return v;
    def getByid(self,imgid):
        res = self.es.get(index=self.index, doc_type=self.type, id=imgid)
        return res;
    def addDoc(self,imgid,jsonbody):
        self.es.index(index=self.index, doc_type=self.type, id=imgid, body=jsonbody)
        return;

    def addTag(self,imgid,tag):
        self.es.update(index=self.index, doc_type=self.type, id=imgid, body={"script": {
            "inline": "ctx._source.tags.add(params.tag)",
            "lang": "painless",
            "params": {
                "tag": tag
            }
        }})
        return;
    def initindex(self):
            self.es.indices.create(index="img_index", body={
                "mappings": {
                    "test_type": {
                        "properties": {
                            "img": {"type": "string"},
                            "tags": {"type": "string"}
                        }

                    }
                }
            },ignore=400)
            return ;

#esoper=Esoper();
body={"img":"cde","tags":["haha"]}
#esoper.addDoc("cde",body)
#esoper.addTag("abc","meiguo");
v=[];
#res=esoper.searchBytag(["dfdfdf"]);
#for hit in res['hits']['hits']:
 #   v.append(hit["_source"])
#print(v);
#esoper.addDoc(body)
#esoper.addTag()



